package com.zthz.douxing.core

import com.zthz.douxing.WeiXinCommand.WeiXinCoreCommand

import java.security.MessageDigest

class WeiXinCoreController {

    private String token = "douxing_weixin_app";

    def checkSignature(WeiXinCoreCommand weiXinCoreCommand){
        if(weiXinCoreCommand.hasErrors()){
            render (weiXinCoreCommand.errors.toString())
            return
        }

        PrintWriter writer = response.getWriter()

        if(verify(weiXinCoreCommand))
            writer.print(weiXinCoreCommand.echostr)

        writer.close()
        writer = null
    }


    private boolean verify(WeiXinCoreCommand weiXinCoreCommand){
        // 微信加密签名
        String signature = weiXinCoreCommand.signature
        // 时间戳
        String timestamp = weiXinCoreCommand.timestamp
        // 随机数
        String nonce = weiXinCoreCommand.nonce
        // 随机字符串
        String echostr = weiXinCoreCommand.echostr

        String[] arr = [token, timestamp, nonce]
        Arrays.sort(arr)

        StringBuffer stringBuffer = new StringBuffer()
        arr.each {String str->
            stringBuffer.append(str)
        }
        MessageDigest md = null
        String tmpStr = null
        try {
            md = MessageDigest.getInstance("SHA-1")
            byte[] digest = md.digest(stringBuffer.toString().getBytes())
            tmpStr = byteToStr(digest);
        } catch (Exception exception) {
            log.error(exception)
        }
        stringBuffer = null
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false
    }

    private String byteToStr(byte[] byteArray) {
        String strDigest = ""
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i])
        }
        return strDigest
    }
    private String byteToHexStr(byte mByte) {
        char[] Digit = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]
        char[] tempArr = new char[2]
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F]
        tempArr[1] = Digit[mByte & 0X0F]

        String s = new String(tempArr)
        return s
    }
}
